<template>
  <el-dialog v-model="accountStore.showRegisterDialog"
             top="50px"
             width="30%"
             :draggable="true"
             @close="handleClose"
             :close-on-click-modal="false">

    <template #header><h2 style="text-align: center; font-size: 1.2rem;font-weight: bold">注册</h2></template>
    <template #default>
      <div class="left-menu">
        <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="120px" style="width: 400px;">
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="form.email"/>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input show-password type="password" v-model="form.password"/>
          </el-form-item>
          <el-form-item label="昵称:" prop="nickname">
            <el-input v-model="form.nickname"/>
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input v-model="form.desc" type="textarea"/>
          </el-form-item>
          <el-form-item label="验证码:" prop="code">
            <el-input style="width: 150px; margin-right: 10px" v-model="form.code"/>
            <el-button style="width: 120px;" :disabled="countDown>0" :loading="getCodeBtn.isLoading" @click="getEmailCode">
              {{ countDown > 0 ? countDown : null }}获取验证码
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button style="width: 280px;" type="primary" @click="onSubmit(ruleFormRef)">注册</el-button>
          </el-form-item>
        </el-form>

      </div>
    </template>

    <template #footer>
      <span @click="toLogin">已有账号</span>
    </template>
  </el-dialog>

</template>

<script setup>
import {reactive, ref} from 'vue'
import {checkEmailApi, registerApi} from "@/api/loginApi.js";
import {getEmailCaptchaApi} from "@/api/captchaApi.js";
import {useAccountStore} from "@/store/accountStore.js";
import {toReactive} from "@vueuse/core";

const accountStore = useAccountStore();
let getCodeBtn = ref({
  isLoading: false,
  disabled: false
})
// 表单数据
let form = reactive({
  email: '',
  password: '',
  nickname: '',
  code: '',
  desc: '',
})
const ruleFormRef = ref()
/**
 * 注册
 * @param formEl
 * @returns {Promise<void>}
 */
const onSubmit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      register()
      accountStore.showRegisterDialog = false
    } else {
      console.log('error submit!', fields)
    }
  })
}
const register = async () => {
  let response = await registerApi(form);
  ElMessage.success(response.message)
}
const toLogin = ()=>{
  accountStore.showRegisterDialog = false
  accountStore.showLoginDialog = true
}
const handleClose = ()=>{
  form = toReactive({})
}
/**
 * 获取验证码
 * @returns {Promise<void>}
 */
const getEmailCode = async () => {
  const emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
  if (!emailReg.test(form.email)) {
    ElMessage.error("邮箱格式错误")
    return
  }
  try {
    getCodeBtn.value.isLoading = true
    let response = await getEmailCaptchaApi(form.email, 0);
    ElMessage.success('验证码发送成功，请查看邮箱')
    limitGetEmailCode()
  } finally {
    getCodeBtn.value.isLoading = false
  }
}
/**
 * 获取邮箱验证码限制
 */
let countDown = ref(0)
const limitGetEmailCode = async () => {
  countDown.value = 30
  let id = setInterval(function () {
    if (countDown <= 0) {
      clearInterval(id)
    }
    countDown.value -= 1
  }, 1000)
}


/**
 * 表单校验规则
 *
 */

const checkEmail = (rules, value, callback) => {
  const emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
  if (!emailReg.test(value)) {
    callback(new Error('邮箱格式错误'))
  }
  callback()
}
const rules = reactive({
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {validator: checkEmail, trigger: 'blur'},
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {min: 6, max: 20, message: "密码应为6-20位字符", trigger: 'blur'},
  ],
  nickname: [
    {required: true, message: '昵称不能为空', trigger: 'blur'},
    {min: 5, max: 20, message: "昵称应为5-10位字符", trigger: 'blur'},
  ],
  code: [
    {required: true, message: '验证码不能为空', trigger: 'blur'},
  ]
})


</script>

<style lang="scss" scoped>
@import "@/styles/var";
span{
  text-decoration: none;
  color: $color-theme;
  cursor: pointer;
}
</style>